import os, sqlite3
from CoreFunctions import GetConfig, GetSetting, MoveFile

class MovieResizer():
    def __init__(self):
        self.DBName         = ""
        if GetConfig('settings.ini'):
            self.MovieFolder    = GetSetting("Common", "MovieFolder")    #"/Movies" #"c:\\temp\\temp"
            self.MovieTypes     = GetSetting("MovieDatabase", "MovieTypes")     #['avi', 'mkv', 'mp4']
            self.DBName         = GetSetting("Common", "DBName")         #"/Movies/Python/MovieDB.db"
            self.OSSeperator    = GetSetting("MovieDatabase", "OSSeperator")    
            self.LogFile        = GetSetting("Common", "LogFile")
            self.Mode           = "Resize"
        self.cn = sqlite3.connect(self.DBName)
        
    def ProcessImages(self):
        SQL = "SELECT Title, MovieCover FROM tblMovies ORDER BY Title"
        self.cursor = self.cn.execute(SQL)
        rows = self.cursor.fetchall()
        
        if rows:
            for row in rows:
                if row[1]!="None":
                    print "Resizing image for '%s' (%s)" % (row[0], row[1])
                    if self.Mode=="Resize":
                        self.ProcessImageFile(row[1])
                    elif self.Mode=="Restore":
                        self.RestoreImageFile(row[1])
        rows = None
        self.cursor = None
        self.cn.close() 
        
    def RestoreImageFile(self, inputfile):
        originalfile = self.MakeOriginalFileName(inputfile)
        if os.path.exists(originalfile)==True:
            outputfile = originalfile.replace(".original.jpg", ".jpg")
            if MoveFile(originalfile, outputfile):
                print "Success"
            else:
                print "Failure"
                
    def MakeOriginalFileName(self, inputfile):
        outputfile      = inputfile #saves confusion!
        inputext        = inputfile[-3:]
        inputfilename   = inputfile[:-3] + "original." + inputext
        return inputfilename 
        
    def ProcessImageFile(self, inputfile):
        """
    
        """
        cmd = """convert.exe """
        
        outputfile      = self.MakeOriginalFileName(inputfile) #saves confusion!
        #inputext        = inputfile[-3:]
        #inputfilename   = inputfile[:-3] + "original." + inputext
        
        if os.path.exists(outputfile)==False:
        
            if MoveFile(inputfile, outputfile):
                print "Success"
                try:
                    cmdtorun = cmd + ' "' + outputfile + '"  -resize 200x300 "' + inputfile + '"'
                    i,k = os.popen4(cmdtorun)
                    i.close()
                    #if split_lines:
                    out = k.readlines()
                    #else:
                    #    out = k.read()
                    k.close()
                    return "OK"
                except Exception, x:
                    #LogError(app='PS2PDF', message='Error converting file %s to PS ' % inputfile, severity=9, errormessage=x, email=False)
                    return "Not OK"
        else:
            print "This image has already been resized..."
            
    def RestoreOriginals(self):
        pass
                
if __name__=="__main__":
    Resizer         = MovieResizer()
    Resizer.Mode    = "Resize"
    Resizer.ProcessImages()    
    